<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        center
      ></el-alert>

      <!-- 步骤条区域 -->
      <el-steps
        :space="200"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab区域 -->
      <el-form
        :model="addGoodForm"
        :rules="addGoodRules"
        ref="addGoodRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabsLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodForm.goods_price"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodForm.goods_weight"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_cat">
              <!-- options用来指定数据源parentCateList -->
              <el-cascader
                v-model="addGoodForm.goods_cat"
                :props="cascaderProps"
                :options="cateList"
                @change="parentCateChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyParams"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  :label="cb"
                  border
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染表单的item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParams"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_name"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialog" width="50%">
      <img :src="previewPath" alt="" width="100%" />
    </el-dialog>
  </div>
</template>


<script>
import _ from "lodash";
export default {
  name: "addGoods",
  data() {
    return {
      activeIndex: "0",
      cateList: [], //分类列表
      //验证规则
      addGoodForm: {
        goods_name: "",
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      addGoodRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      cateKeys: [], //所选择的分类id 数组
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyParams: [],
      onlyParams: [],
      checked: false,
      fileList: [],
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPath: "",
      previewDialog: false,
    };
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      return this.addGoodForm.goods_cat[2];
    },
  },
  methods: {
    //获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取分类列表失败！");
      this.cateList = res.data;
      //    console.log(this.cateList);
    },
    //级联选择器发生变化
    parentCateChange() {
      if (this.addGoodForm.goods_cat.length !== 3) {
        this.addGoodForm.goods_cat = [];
      }
    },
    beforeTabsLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addGoodForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    //tab标签点击触发事件
    async tabClicked() {
      //获取动态参数
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        //将属性分割成数组
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        console.log(res.data);
        this.manyParams = res.data;
      }
      if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        this.onlyParams = res.data;
        console.log(res.data);
      }
    },
    //点击图片预览
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.previewDialog = true;
    },
    //点击移除图片
    handleRemove(file) {
      const filePath = file.response.data.tmp_path;
      const i = this.addGoodForm.pics.findIndex((x) => x === filePath);
      this.addGoodForm.pics.splice(i, 1);
    },
    //图片上传成功的钩子
    handleSuccess(res) {
      const picsInfo = res.data.tmp_path;
      this.addGoodForm.pics.push(picsInfo);
      console.log(this.addGoodForm);
    },
    addGoods() {
      // 进行表单与验证
      this.$refs.addGoodRef.validate(async (valid) => {
        if (!valid) return;
        //数据处理
        const form = _.cloneDeep(this.addGoodForm);
        //处理动态参数
        console.log(this.manyParams);
        console.log(this.onlyParams);
        this.manyParams.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          form.attrs.push(newInfo);
        });

        // 处理静态属性
        this.onlyParams.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          form.attrs.push(newInfo);
        });
        // 发起请求
        form.goods_cat = form.goods_cat.join(",");
        // console.log(form.goods_cat);

        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) return this.$message.error("添加失败！");
        this.$message.success("添加成功！");
        this.$router.push("/goods");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-step__title {
  font-size: 14px !important;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-button {
  margin: 15px 0;
}
</style>